// pages/teamDetail/teamDetail.js
import { reLogin } from '../../service/request'
import activityApi from '../../service/activityApi'
import sweepstakeApi from '../../service/sweepstakeApi'
import { parseQuery } from '../../utils/util'

const app = getApp()
let iptNumberComponent // 数字输入框组件实例
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showTeamIntroMoreFlag: false, // 是否展示更多战队介绍
    showProjectIntroMoreFlag: false, // 是否展示更多作品介绍
    haveMoreDescFlag: false, // 简介是否超出两行了
    teamInfo: {
      teamLogo: '',
      teamName: '',
      school: '',
      voteCount: '',
      teamNo: '',
      projectBrief: '',
      shareUserId: ''
    },
    hadAuthFlag: false, // 是否授权
    showSharePopFlag: false, // 展示分享弹窗
    showVotePopFlag: false, // 展示投票弹窗
    voteLoading: false, // 投票loading
    availableVoteLoading: false, // 可用投票loading
    voteDisabled: false, // 不可用投票
    shareLoading: false, // 分享 loading
    maxStock: '9999',
    rewardMultiple: '0',
    userId: '',
    availableVoteCount: 0,
    voteInfo: {
      teamNo: '',
      teamLogo: '',
      voteCount: '',
      shareUserId: '' // 分享者Id
    },
    matchStatus: app.globalData.codeConfig.matchStatus.REMATCH_VOTE_OPEN, // 大赛投票状态
    matchStatusEnum: app.globalData.codeConfig.matchStatus // 大赛投票状态枚举
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let sceneObj = {}
    if (options.scene) {
      sceneObj = parseQuery(options.scene)
      console.log(sceneObj)
    }
    if (options.teamNo) {
      this.setData({
        ['teamInfo.teamNo']: options.teamNo
      })
    } else if (options.scene && sceneObj.teamNo) {
      this.setData({
        ['teamInfo.teamNo']: sceneObj.teamNo
      })
    }
    if (options.matchStatus) {
      this.setData({
        matchStatus: options.matchStatus
      })
    }
    if (options.userId) {
      this.setData({
        ['voteInfo.shareUserId']: options.userId
      })
    }
    wx.hideShareMenu()
    iptNumberComponent = this.selectComponent('#ipt-quantity') // 获取数字输入框实例
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkStatus()
  },
  // 授权状态的检查
  checkStatus () {
    let that = this
    // 判断是否有授权，有授权的话从回调调用方法初始化数据
    // 无授权的话直接调用方法初始化数据
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            hadAuthFlag: true
          })
          if (wx.getStorageSync('token')) {
            that.getTeamDetail()
          } else {
            app.checkStatusCallback = res => {
              that.setData({
                userInfo: res,
                hasUserInfo: true
              })
              that.getTeamDetail()
            }
          }
        } else {
          that.getTeamDetail()
        }
      }
    })
  },
  handleShowMore (e) {
    let type = e.currentTarget.dataset.type
    if (type === 'team') {
      this.setData({
        showTeamIntroMoreFlag: !this.data.showTeamIntroMoreFlag
      })
    } else if (type === 'project') {
      this.setData({
        showProjectIntroMoreFlag: !this.data.showProjectIntroMoreFlag
      })
    }
  },
  getTeamDetail () {
    let that = this
    activityApi.getTeamDetail({
      teamNo: that.data.teamInfo.teamNo
    }).then((res) => {
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        that.setData({
          teamInfo: {...res.data.data}
        })
      }
    })
  },
  // 获取用户信息回调
  bindGetUserInfo (e) {
    let that = this
    // that.showConfrimLoading()
    console.log(e.detail.userInfo)
    if (!!e.detail.userInfo) { // 同意授权-并登陆
      wx.setStorageSync('hadAuthFlag', true)
      app.globalData.userInfo = e.detail.userInfo
      app.globalData.hadAuthUserInfo = true
      reLogin().then(() => {
        // that.hideConfrimLoading()
        that.setData({
          hadAuthFlag: true
        })
        // that.handleConfirmBuy()
        console.log(app.globalData.userInfo)
      }).catch((res) => {
        // that.hideConfrimLoading()
      })
    } else { // 不同意授权
      // that.hideConfrimLoading()
      wx.setStorageSync('hadAuthFlag', false)
      that.setData({
        hadAuthFlag: false
      })
    }
  },
  // 打开分享弹窗
  handleShowSharePop () {
    if (!this.data.hadAuthFlag) return
    if ( // 决赛名单未公示和已公示
      (this.data.matchStatus - 0) === this.data.matchStatusEnum.REMATCH_LIST_NOT_PUBLIC ||
      (this.data.matchStatus - 0) === this.data.matchStatusEnum.REMATCH_LIST_PUBLIC
    ) {
      wx.showToast({
        icon: 'none',
        title: '请等待决赛开启'
      })
      return
    } else if ((this.data.matchStatus - 0) === this.data.matchStatusEnum.REMATCH_VOTE_CLOSE) {
      wx.showToast({
        icon: 'none',
        title: '决赛投票已结束'
      })
      return
    }
    this.getRewardMultiple()
  },
  // 关闭分享弹窗
  handleCloseSharePop () {
    this.setData({
      showSharePopFlag: false
    })
  },
  // 获取中奖倍率
  getRewardMultiple () {
    let that = this
    if (that.data.shareLoading) return
    that.setData({
      shareLoading: true
    })
    wx.showLoading({
      title: '',
      mask: true
    })
    sweepstakeApi.getRewardMultiple().then((res) => {
      that.setData({
        shareLoading: false
      })
      wx.hideLoading()
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        that.setData({
          rewardMultiple: res.data.data.multiple,
          userId: res.data.data.userId
        })
        if (that.data.rewardMultiple === '0') {
          wx.showToast({
            icon: 'none',
            title: '请先投票'
          })
        } else {
          that.setData({
            showSharePopFlag: true
          })
        }
      }
    }).catch((res) => {
      wx.hideLoading()
      that.setData({
        shareLoading: false
      })
    })
  },
  // 打开投票弹窗
  handleShowVotePop (e) {
    this.setData({
      ['voteInfo.teamNo']: e.currentTarget.dataset.teamno
    })
    this.getAvailableVoteCount()
  },
  // 关闭投票弹窗
  handleCloseVotePop () {
    this.setData({
      showVotePopFlag: false
    })
  },
  // 获取剩余投票数
  getAvailableVoteCount () {
    let that = this
    that.setData({
      showVotePopFlag: true,
      availableVoteLoading: true
    })
    activityApi.getAvailableVoteNum().then((res) => {
      that.setData({
        availableVoteLoading: false
      })
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        let availableVote = res.data.data.availableVote
        that.setData({ 
          availableVoteCount: availableVote,
          maxStock: availableVote,
          ['voteInfo.voteCount']: availableVote
        })
        // 调用数字输入框组件的方法更新 sub 和 add 按钮禁用状态
        iptNumberComponent.updated(that.data.voteInfo.voteCount)
        if ((availableVote - 0) === 0) {
          that.setData({
            voteDisabled: true
          })
        } else {
          that.setData({
            voteDisabled: false
          })
        }
      }
    }).catch((res) => {
      that.setData({
        availableVoteLoading: false
      })
    })
  },
  // 输入的票数改变触发
  handleQuantityChange (e) {
    this.setData({
      ['voteInfo.voteCount']: e.detail.value
    })
  },
  // 点击被禁用的加按钮触发
  handleDisableAdd () {
    //
  },
  // 投票
  handleVote () {
    let that = this
    if (that.data.availableVoteLoading || that.data.voteLoading || that.data.voteDisabled) return
    that.setData({
      voteLoading: true
    })
    activityApi.vote({...that.data.voteInfo}).then((res) => {
      that.setData({
        voteLoading: false
      })
      console.log(res)
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        that.setData({
          showVotePopFlag: false
        })
        wx.navigateTo({
          url: '/pages/voteResult/voteResult?page=detail&teamName='
                + that.data.teamInfo.teamName + '&teamNo=' +
                that.data.teamInfo.teamNo
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: res.data.msg
        })
      }
    }).catch((res) => {
      that.setData({
        voteLoading: false
      })
    })
  },
  handleAddVoteCount () {
    this.setData({
      showVotePopFlag: false
    })
    wx.navigateTo({
      url: "/pages/task/task"
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this
    this.setData({
      showSharePopFlag: false
    })
    return {
      title: `“${that.data.teamInfo.teamName}”战队需要您的一票之力！可领600元全额抵扣券！`,
      imageUrl: app.globalData.picBaseUrl + '/vote/20190506/mzR2vJap7IWC.png',
      path: '/pages/index/index?targetPage=teamDetail&userId=' + that.data.userId + '&teamNo=' + that.data.teamInfo.teamNo
    }
  }
})